﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows;

namespace Snowdreamist.Windows.Data
{
    public class LanguageResources : List<LanguageResource> { }

    public abstract class LanguageResource
    {
        public abstract CultureInfo GetCulture();

        public abstract object GetResource(string key);
    }

    public class LanguageResourceDictionary : LanguageResource
    {
        public override CultureInfo GetCulture()
        {
            return CultureInfo.CreateSpecificCulture(this.CultureName);
        }

        public override object GetResource(string key)
        {
            if (this.Dictionary == null)
                this.LoadDictionary();
            if (this.Dictionary == null || !this.Dictionary.Contains(key))
                return null;
            return this.Dictionary[key];
        }

        public string CultureName { get; set; }

        public ResourceDictionary Dictionary { get; set; }

        public Uri DictionaryUri
        {
            get
            {
                return this._uri;
            }
            set
            {
                if (this._uri != value)
                {
                    this._uri = value;
                    this._isFailed = false;
                }
            }
        }

        private void LoadDictionary()
        {
            if (!this._isFailed && this.DictionaryUri != null)
            {
                try
                {
                    if (this.Dictionary == null)
                        lock (this)
                            if (this.Dictionary == null)
                                this.Dictionary = XamlResourcesHelper.LoadResourceDictionary(this.DictionaryUri);
                }
                catch (Exception error)
                {
                    this._isFailed = true;
                    Trace.WriteLine("LanguageResourceDictionary:LoadDictionary failed.\n" + error.ToString());
                }
            }
        }

        private Uri _uri;

        private bool _isFailed = false;
    }
}